package spring.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import spring.dao.UserDao;
import spring.dao.impl.UserDaoImpl;
import spring.entity.User;
import spring.factory.UserDaoFactory;
import spring.service.UserService;
import utils.MyBatisUtil;

import javax.annotation.Resource;

/**
 * @author 吴阳基
 * @datetime 2024/1/9 13:56
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    private static final Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    private UserDao dao;

    public UserServiceImpl() {
    }

    public UserServiceImpl(UserDao dao) {
        this.dao = dao;
    }


    public boolean save(User user) {
        logger.info("添加用户" + user.getUsername() + "到数据库");
        SqlSession sqlSession = null;
        boolean flag = false;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            if (sqlSession.getMapper(UserDao.class).save(user) > 0)
                flag = true;
            sqlSession.commit();
            logger.info("添加用户" + user.getUsername() + "到数据库成功");
        } catch (Exception e) {
            logger.error("添加用户" + user.getUsername() + "到数据库失败");
            sqlSession.rollback();
            flag = false;
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return flag;
    }

    public void setUserDao(UserDao userDao) {

        this.dao = userDao;
    }

    /**
     * 获取
     * @return dao
     */
    public UserDao getDao() {
        return dao;
    }

    /**
     * 设置
     * @param dao
     */
    public void setDao(UserDao dao) {
        this.dao = dao;
    }

    public String toString() {
        return "UserServiceImpl{logger = " + logger + ", dao = " + dao + "}";
    }
}
